/**
 *  * @brief 动态决定创建线程的个数
 *   */

#include<iostream>
#include<thread>
#include<algorithm>
#include<numeric>
#include<vector>
#include<array>
#include<list>

int64_t AccumBlock(int64_t* first, int64_t* last, int64_t& result)
{
	result = std::accumulate(first, last, result);
	return result;
}

int GenValue(void)
{
	static int i = 1;
	return i++;
}

int main(void)
{
	constexpr int num_size = 1000000;
	std::vector<int64_t> ivec(num_size);
	std::generate(ivec.begin(), ivec.end(), GenValue);

	int best_thread_num = std::thread::hardware_concurrency();
	if (best_thread_num < 2)
	{
		best_thread_num = 4;
	}
	--best_thread_num;		//主线程要占用一个线程

	std::vector<int64_t> result(best_thread_num);
	std::vector<std::thread> sub_thread(best_thread_num);

	int accu_num = num_size / best_thread_num;
	int left_num = num_size - accu_num * (best_thread_num - 1);

	int64_t* first = &ivec[0];
	int64_t* last = first + accu_num;
	for (int i = 0; i < best_thread_num - 1; i++)
	{
		sub_thread[i] = std::thread(AccumBlock, first, last, std::ref(result[i]));
		first = last;
		last += accu_num;
	}

	sub_thread[best_thread_num - 1] = std::thread(AccumBlock, first, &ivec[0] + num_size, std::ref(result[best_thread_num - 1]));

	std::for_each(sub_thread.begin(), sub_thread.end(), std::mem_fn(&std::thread::join));

	int64_t total_res = 0;
	total_res = AccumBlock(&result[0], &result[0] + best_thread_num, total_res);
	std::cout << total_res << std::endl;
}

